/**
 * 公用的头部导航
 */
define(function (require) {
    'use strict';
    var $ = require('jquery');
    var _ = require('underscore');
    var util = require('/static_public/js/util');
    var environment = require('environment');
    var qmyxHost = environment.qmyx;
    require('/static_public/js/token');

    // http://localhost:8088/index.html -> /index.html
    var PATH_REGEX = /^http:\/\/.*?(\/.*)/;
    var menuObj = {
        selector : '.top-menu',
        hasMvp : false,//买了mvp
        notMvp : false,
        onlyMvp : false,
        notYdxs : false,
        getMapData : function(){
            return {
                'zsslc' : {
                    id : 'zsslc',
                    name : '掌上售楼处',
                    url : qmyxHost+'/page/palm_sales/index.shtml',
                    selects : ['/page/palm_sales/','/page/raise_finance/','/wls/index.html'],
                    sort : 1
                },
                'qdgj' : {
                    id : 'qdgj',
                    name : '渠道管家',
                    url : qmyxHost+'/page/home/home.shtml',
                    selects : ['/page/houses_project/','/page/intermediary_organ/','/page/third_channel/',
                        '/page/customer_management/','/page/ditch/source.shtml','/page/brokerage/','/page/encouragement/',
                        '/page/brokerage/','/page/reports/','/page/maintenance/',
                        '/page/config/content/','/page/parameter_settings/','/page/custom-page/',
                        '/page/finance/',
                        '/page/game_rules/',
                        '/page/intermediary_organ/bee/index.shtml'],
                    sort : 2
                },
                'ydxs' : {
                    id : 'ydxs',
                    name : '移动销售',
                    url: qmyxHost + '/page/customer_distribution/index.html',
                    selects : ['/ydxs_static/page/','/page/wangcaibao/'],
                    sort : 3
                },
                'hdcb' : {
                    id : 'hdcb',
                    name : '互动传播',
                    url : qmyxHost+'/page/app_store/index.shtml',
                    selects : ['/page/o2o_application/'],
                    sort : 4
                }
            };
        },
        getMenuOnClass : function(menu){
            var selects = (menu.selects || []),on='';
            var urlMatch = menu.url.match(PATH_REGEX);
            if(urlMatch && urlMatch.length>1){
                selects.push(urlMatch[1]);
            }
            $.each(selects,function(){
                if(location.pathname.indexOf(this) !== -1){
                    on = 'menu-on';
                    return false;
                }
            });
            if(!on){
                on = this.extraMenuOnClass(menu);
            }
            return on ;
        },
        extraMenuOnClass : function(menu){
            var hasMvp = this.hasMvp, notYdxs = this.notYdxs,notMvp = this.notMvp,on = '';
            // 移动销售简版菜单
            if(menu.id === 'zsslc' && hasMvp && notYdxs){
                var ydxsObj = this.getMapData().ydxs;
                var selects = (ydxsObj.selects || []);
                var urlMatch = ydxsObj.url.match(PATH_REGEX);
                if(urlMatch && urlMatch.length>1){
                    selects.push(urlMatch[1]);
                }
                $.each(selects,function(){
                    if(location.pathname.indexOf(this) !== -1){
                        on = 'menu-on';
                        return false;
                    }
                });
            }
            if(menu.id === 'hdcb' && notMvp){
                if(location.pathname.indexOf('/wls/index.html') !== -1){
                    on = 'menu-on';
                }
            }
            return on;
        },
        menuMapping : function(data){
            var mapData = this.getMapData();
            var menus = [mapData.hdcb];
            _.each(data,function(val){
                var menu = mapData[val.unique_name];
                if(menu){
                    menus.push(menu);
                }
            });
            return menus;
        },
        buildMenu : function(menus){
            var lis = '';
            _.each(menus,function(menu){
                var tokenStr = '';
                if(menu.needToken === false){
                    tokenStr = 'data-no-token';
                }
                var on = menuObj.getMenuOnClass(menu);
                lis += '<li class="'+on+'" ><a href="'+menu.url+'" '+tokenStr+' class="fl f16 c-white">'+menu.name+'</a></li>';
            });
            return lis;
        },
        authorityMenu : function(menus){
            var style = '';
            var zsslc = _.find(menus,function(obj){ return obj.id === 'zsslc';});

            var ydxs = _.find(menus,function(obj){ return obj.id === 'ydxs';});

            var qdgj = _.find(menus,function(obj){ return obj.id === 'qdgj';});

            //zsslc = false ,ydxs = false, qdgj = true;

            if(zsslc){// has zsslc
                this.hasMvp = true;
                style += '#nav .has-mvp{display:block !important}';
            }else{
                this.notMvp = true;
                style += '#nav .not-mvp{display:block !important}';
            }

            if(ydxs){
                style += '#nav .has-ydxs{display:block !important}';
            }

            if(zsslc && !ydxs){// has zsslc,not ydxs
                this.notYdxs = true;
                style += '#nav .not-ydxs{display:block !important}';
            }

            if(zsslc && !ydxs && !qdgj ){//only zsslc
                this.onlyMvp = true;
                style += '#nav .only-mvp{display:block !important}';
            }

            if(zsslc && qdgj && !ydxs){
                style += '#nav .mvp-qdgj{display:block !important}';
            }

            if(zsslc && ydxs && qdgj){
                style += '#nav .mvp-ydxs-qdgj{display:block !important}';
            }
            $('head').append('<style type="text/css">' + style + '</style>');
        },
        bindEvent: function(){
            $(menuObj.selector).on('click', 'a', function (e) {
                //如果与目前导航地址一致，则禁止浏览器默认行为
                var url = $(this).attr('href');
                url = util.setUrlPara('token', util.getToken(), url);

                var urlObj = util.getUrlObj(url);
                if (urlObj.pathname + '?' + urlObj.search === location.pathname + location.search) {
                    e.preventDefault();
                    location.reload();
                }
            });
        },
        loadPackageList : function(){

            var apiPrefix = '/api/index.php?r=';
            var url = qmyxHost + apiPrefix + 'project/auth/get-buy-package-list';

            $.ajax({
                url:url,
                dataType:'jsonp',
                jsonp:'callback',
                data : {
                    token : util.getToken()
                },
                success:function(result) {
                    //数据映射
                    var menus = menuObj.menuMapping(result.data || []);

                    //菜单排序
                    menus = _.sortBy(menus,'sort');

                    //菜单权限分析
                    menuObj.authorityMenu(menus);

                    //生成菜单
                    var lis = menuObj.buildMenu(menus);

                    //插入菜单
                    $(menuObj.selector).append(lis);

                    // bind event
                    menuObj.bindEvent();
                },
                error : function(jqXHR, textStatus, errorThrown){
                    console.error(errorThrown);
                },
                timeout:10000
            });
        },
        initTop : function(){
            $('head').append('<style type="text/css">#nav .c-mvp{display:none !important}</style>');

            var selector = this.selector;

            var html = '<li ><a href="'+qmyxHost+'/index.shtml" class="fl f16 c-white" data-no-token>云客首页</a></li>';
            $(selector).append(html);//云客首页为必须的

            this.loadPackageList();//加载包数据
        }
    };
    try {
        menuObj.initTop();
    } catch (e) {
        console.error(e);
        util.notify('顶部菜单初始化失败！');
    }
});